/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.tlf.dyjc5.servlet.data;

import com.tlf.dyjc5.service.YsjService;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.dusin.db.exception.AlreadLockedException;
import org.dusin.web.util.CommonWebUtil;
import org.dusin.web.util.JsonUtil;
import org.dusin.web.util.TheUtil;
import org.springframework.context.ApplicationContext;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 *
 * @author Administrator
 */
public class YsjSave extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
            YsjService ysjService = (YsjService) context.getBean("ysjService");
            String msg = null;
            String command = request.getParameter("cmd");
            boolean result = false;
            String lock = request.getParameter("lock");
            String currentOrgCode = (String) request.getSession().getAttribute("currentOrgCode");
            if ("create".equals(command) || "createLock".equals(command)) {
                String deviceIdStr = request.getParameter("deviceId");
                long deviceId = CommonWebUtil.getLongParameter(deviceIdStr, 0);

                String pointIdStr = request.getParameter("pointId");
                long pointId = CommonWebUtil.getLongParameter(pointIdStr, 0);

                String defaultTotalTimeStr = request.getParameter("defaultTotalTime");
                long defaultTotalTime = CommonWebUtil.getLongParameter(defaultTotalTimeStr, 1);

                String aboveUpperLimitNumberStr = request.getParameter("aboveUpperLimitNumber");
                int aboveUpperLimitNumber = CommonWebUtil.getIntParameter(aboveUpperLimitNumberStr, 0);

                String underLowerLimitNumberStr = request.getParameter("underLowerLimitNumber");
                int underLowerLimitNumber = CommonWebUtil.getIntParameter(underLowerLimitNumberStr, 0);

                String dataYearStr = request.getParameter("dataYear");
                int dataYear = CommonWebUtil.getIntParameter(dataYearStr, 0);

                String dataMonthStr = request.getParameter("dataMonth");
                int dataMonth = CommonWebUtil.getIntParameter(dataMonthStr, 0);

                String typeStr = request.getParameter("type");
                int type = CommonWebUtil.getIntParameter(typeStr, 0);

                String totalRunMinStr = request.getParameter("totalRunMin");
                long totalRunMin = CommonWebUtil.getLongParameter(totalRunMinStr, 1);

                String aboveUpperLimitMinStr = request.getParameter("aboveUpperLimitMin");
                long aboveUpperLimitMin = CommonWebUtil.getLongParameter(aboveUpperLimitMinStr, 0);

                String underLowerLimitMinStr = request.getParameter("underLowerLimitMin");
                long underLowerLimitMin = CommonWebUtil.getLongParameter(underLowerLimitMinStr, 0);

                String maxVoltageStr = request.getParameter("maxVoltage");
                double maxVoltage = CommonWebUtil.getDoubleParameter(maxVoltageStr, 0);

                String minVoltageStr = request.getParameter("minVoltage");
                double minVoltage = CommonWebUtil.getDoubleParameter(minVoltageStr, 0);

                String avgVoltageStr = request.getParameter("avgVoltage");
                double avgVoltage = CommonWebUtil.getDoubleParameter(avgVoltageStr, 0);

                String statusStr = request.getParameter("status");
                int status = CommonWebUtil.getIntParameter(statusStr, 0);

                String reasonAnalyze = request.getParameter("reasonAnalyze");

                String treatWay = request.getParameter("treatWay");

                String completeCase = request.getParameter("completeCase");

                String note = request.getParameter("note");

                String dataTimeStr = request.getParameter("dataTime");
                Timestamp dataTime = CommonWebUtil.getTimestampParamter(dataTimeStr);

                String maxVoltageDateStr = request.getParameter("maxVoltageDate");

                String maxVoltageTimeStr = request.getParameter("maxVoltageTime");
                maxVoltageTimeStr = maxVoltageDateStr + " " + maxVoltageTimeStr;
                Timestamp maxVoltageTime = CommonWebUtil.getTimestampParamter(maxVoltageTimeStr);

                String minVoltageDateStr = request.getParameter("minVoltageDate");

                String minVoltageTimeStr = request.getParameter("minVoltageTime");
                minVoltageTimeStr = minVoltageDateStr + " " + minVoltageTimeStr;
                Timestamp minVoltageTime = CommonWebUtil.getTimestampParamter(minVoltageTimeStr);
                if(ysjService.isLock(currentOrgCode, dataYear, dataMonth,lock)){
                    throw new AlreadLockedException();
                }

                if ("create".equals(command)) {

                    result = ysjService.add(deviceId, pointId, dataYear, dataMonth, dataTime, type, aboveUpperLimitNumber, underLowerLimitNumber,
                            defaultTotalTime, totalRunMin, aboveUpperLimitMin, underLowerLimitMin, maxVoltage, maxVoltageTime, minVoltage,
                            minVoltageTime, avgVoltage, reasonAnalyze, treatWay, completeCase, note);
                } else {
                    String pointCode = request.getParameter("pointCode");
                    String companyCode = request.getParameter("companyCode");
                    String orgCode = request.getParameter("orgCode");
                    String company = request.getParameter("company");
                    String subCompany=request.getParameter("subCompany");
                    String station = request.getParameter("station");
                    String name = request.getParameter("name");
                    String pointArea = request.getParameter("pointArea");
                    String pointPosition = request.getParameter("pointPosition");
                    int pointTypeId = CommonWebUtil.getIntParameter(request.getParameter("pointTypeId"), 0);
                    String pointType = request.getParameter("pointType");
                    int pointType2Id = CommonWebUtil.getIntParameter(request.getParameter("pointType2Id"), 0);
                    String pointType2 = request.getParameter("pointType2");
                    double lowerLimit = CommonWebUtil.getDoubleParameter(request.getParameter("lowerLimit"), 0);
                    double upperLimit = CommonWebUtil.getDoubleParameter(request.getParameter("upperLimit"), 0);
                    
                    int startStatus = CommonWebUtil.getIntParameter(request.getParameter("startStatus"), 0);
                    int reportStatus = CommonWebUtil.getIntParameter(request.getParameter("reportStatus"), 0);
                    int pointStatus = reportStatus*10+startStatus;
                    
                    int orgTypeId = CommonWebUtil.getIntParameter(request.getParameter("orgTypeId"), 0);
                    String orgTypeName = request.getParameter("orgTypeName");
                    double voltage = CommonWebUtil.getDoubleParameter(request.getParameter("voltage"), 0);
                    double voltageLevelValue  = CommonWebUtil.getDoubleParameter(request.getParameter("voltageLevelValue"), 0);
                    int voltageLevelId = CommonWebUtil.getIntParameter(request.getParameter("voltageLevelId"), 0);
                    String voltageLevelName = request.getParameter("voltageLevelName");
                    aboveUpperLimitNumber=0;
                    underLowerLimitNumber=0;
                    defaultTotalTime =0;
                    
                    result = ysjService.addLock(deviceId, pointId, dataYear, dataMonth, dataTime, type,totalRunMin, 
                            aboveUpperLimitMin, underLowerLimitMin, maxVoltage, maxVoltageTime, minVoltage,
                            minVoltageTime, avgVoltage,aboveUpperLimitNumber,underLowerLimitNumber,defaultTotalTime,"",  treatWay, completeCase, note
                            ,orgCode,company,subCompany,station,name,pointArea,pointPosition,pointTypeId,pointType,pointType2Id,pointType2,lowerLimit,
                            upperLimit,pointStatus,orgTypeId,orgTypeName,voltage,voltageLevelValue,voltageLevelId,voltageLevelName,pointCode,companyCode);
                }
            } else if ("update".equals(command) || "updateLock".equals(command)) {
                long id = Long.parseLong(request.getParameter("id"));
                String deviceIdStr = request.getParameter("deviceId");
                long deviceId = CommonWebUtil.getLongParameter(deviceIdStr, 0);

                String pointIdStr = request.getParameter("pointId");
                long pointId = CommonWebUtil.getLongParameter(pointIdStr, 0);

                String defaultTotalTimeStr = request.getParameter("defaultTotalTime");
                long defaultTotalTime = CommonWebUtil.getLongParameter(defaultTotalTimeStr, 1);

                String aboveUpperLimitNumberStr = request.getParameter("aboveUpperLimitNumber");
                int aboveUpperLimitNumber = CommonWebUtil.getIntParameter(aboveUpperLimitNumberStr, 0);

                String underLowerLimitNumberStr = request.getParameter("underLowerLimitNumber");
                int underLowerLimitNumber = CommonWebUtil.getIntParameter(underLowerLimitNumberStr, 0);

                String dataYearStr = request.getParameter("dataYear");
                int dataYear = CommonWebUtil.getIntParameter(dataYearStr, 0);

                String dataMonthStr = request.getParameter("dataMonth");
                int dataMonth = CommonWebUtil.getIntParameter(dataMonthStr, 0);

                String typeStr = request.getParameter("type");
                int type = CommonWebUtil.getIntParameter(typeStr, 0);

                String totalRunMinStr = request.getParameter("totalRunMin");
                long totalRunMin = CommonWebUtil.getLongParameter(totalRunMinStr, 1);

                String aboveUpperLimitMinStr = request.getParameter("aboveUpperLimitMin");
                long aboveUpperLimitMin = CommonWebUtil.getLongParameter(aboveUpperLimitMinStr, 0);

                String underLowerLimitMinStr = request.getParameter("underLowerLimitMin");
                long underLowerLimitMin = CommonWebUtil.getLongParameter(underLowerLimitMinStr, 0);

                String maxVoltageStr = request.getParameter("maxVoltage");
                double maxVoltage = CommonWebUtil.getDoubleParameter(maxVoltageStr, 0);

                String minVoltageStr = request.getParameter("minVoltage");
                double minVoltage = CommonWebUtil.getDoubleParameter(minVoltageStr, 0);

                String avgVoltageStr = request.getParameter("avgVoltage");
                double avgVoltage = CommonWebUtil.getDoubleParameter(avgVoltageStr, 0);

                String statusStr = request.getParameter("status");
                int status = CommonWebUtil.getIntParameter(statusStr, 0);

                String reasonAnalyze = request.getParameter("reasonAnalyze");

                String treatWay = request.getParameter("treatWay");

                String completeCase = request.getParameter("completeCase");

                String note = request.getParameter("note");

                String dataTimeStr = request.getParameter("dataTime");
                Timestamp dataTime = CommonWebUtil.getTimestampParamter(dataTimeStr);

                String maxVoltageDateStr = request.getParameter("maxVoltageDate");

                String maxVoltageTimeStr = request.getParameter("maxVoltageTime");
                maxVoltageTimeStr = maxVoltageDateStr + " " + maxVoltageTimeStr;
                Timestamp maxVoltageTime = CommonWebUtil.getTimestampParamter(maxVoltageTimeStr);

                String minVoltageDateStr = request.getParameter("minVoltageDate");

                String minVoltageTimeStr = request.getParameter("minVoltageTime");
                minVoltageTimeStr = minVoltageDateStr + " " + minVoltageTimeStr;
                Timestamp minVoltageTime = CommonWebUtil.getTimestampParamter(minVoltageTimeStr);

                if ("update".equals(command)) {
                    result = ysjService.update(id, dataTime, type, aboveUpperLimitNumber, underLowerLimitNumber, defaultTotalTime, totalRunMin, aboveUpperLimitMin,
                            underLowerLimitMin, maxVoltage, maxVoltageTime, minVoltage, minVoltageTime, avgVoltage, reasonAnalyze, treatWay, completeCase, note, status);
                } else {

                    result = ysjService.updateLockByKey(deviceId, dataTime, type, aboveUpperLimitNumber, underLowerLimitNumber, defaultTotalTime, totalRunMin, aboveUpperLimitMin,
                            underLowerLimitMin, maxVoltage, maxVoltageTime, minVoltage, minVoltageTime, avgVoltage, pointId, dataYear, dataMonth);
                }
            } else if ("reason".equals(command)) {
                String id = request.getParameter("id");
                String reasonAnalyze = request.getParameter("reasonAnalyze");
                String treatWay = request.getParameter("treatWay");
                String completeCase = request.getParameter("completeCase");
                result = ysjService.updateReason(id, reasonAnalyze, treatWay, completeCase);

            } else if ("remove".equals(command)) {                
                String pointIdStr = request.getParameter("pointId");
                long pointId = CommonWebUtil.getLongParameter(pointIdStr, 0);
                String dataYearStr = request.getParameter("dataYear");
                int dataYear = CommonWebUtil.getIntParameter(dataYearStr, 0);

                String dataMonthStr = request.getParameter("dataMonth");
                int dataMonth = CommonWebUtil.getIntParameter(dataMonthStr, 0);
                
                if(ysjService.isLock(currentOrgCode, dataYear, dataMonth,lock)){
                    throw new AlreadLockedException();
                }
                
                result = ysjService.deleteByKey(pointId, dataYear, dataMonth,lock);

            }  else if ("removeAll".equals(command)) {
                
                String dateFrom = request.getParameter("dateFrom");
                String dateTo = request.getParameter("dateTo");
                String condition = TheUtil.getPointSelectCondition(request);
                result = ysjService.trDeleteAll(currentOrgCode, dateFrom, dateTo, condition, lock);

            } else if ("yRateSet".equals(command)) {
                String date = request.getParameter("dateTo");
                String condition = TheUtil.getPointSelectCondition(request);
                String rateStr = request.getParameter("rate");
                //sb.append(" and startStatus=1");

                result = ysjService.updateAllByRateV2(currentOrgCode, date, condition, Double.parseDouble(rateStr));
            } else if ("batchCreateLock".equals(command)) {

                String date = request.getParameter("dateTo");
                String condition = TheUtil.getPointSelectCondition(request);
                //String rateStr = request.getParameter("rate");
                String rateStr = "0.95";
                //sb.append(" and startStatus=1");                
                result = ysjService.trBatchCreate(currentOrgCode, date, condition, Double.parseDouble(rateStr),lock);
            }else if("recallSave".equals(command)){ //召回数据保存
                String deviceIdStr = request.getParameter("deviceId");
                long deviceId = CommonWebUtil.getLongParameter(deviceIdStr, 0);

                String pointIdStr = request.getParameter("pointId");
                long pointId = CommonWebUtil.getLongParameter(pointIdStr, 0);

                
                long defaultTotalTime = 1;

                String aboveUpperLimitNumberStr = request.getParameter("aboveUpperLimitNumber");
                int aboveUpperLimitNumber = CommonWebUtil.getIntParameter(aboveUpperLimitNumberStr, 0);

                String underLowerLimitNumberStr = request.getParameter("underLowerLimitNumber");
                int underLowerLimitNumber = CommonWebUtil.getIntParameter(underLowerLimitNumberStr, 0);

                String dataYearStr = request.getParameter("dataYear");
                int dataYear = CommonWebUtil.getIntParameter(dataYearStr, 0);

                String dataMonthStr = request.getParameter("dataMonth");
                int dataMonth = CommonWebUtil.getIntParameter(dataMonthStr, 0);

                
                int type = 0;

                String totalRunMinStr = request.getParameter("totalRunMin");
                long totalRunMin = CommonWebUtil.getLongParameter(totalRunMinStr, 1);

                String aboveUpperLimitMinStr = request.getParameter("aboveUpperLimitMin");
                long aboveUpperLimitMin = CommonWebUtil.getLongParameter(aboveUpperLimitMinStr, 0);

                String underLowerLimitMinStr = request.getParameter("underLowerLimitMin");
                long underLowerLimitMin = CommonWebUtil.getLongParameter(underLowerLimitMinStr, 0);

                String maxVoltageStr = request.getParameter("maxVoltage");
                double maxVoltage = CommonWebUtil.getDoubleParameter(maxVoltageStr, 0);

                String minVoltageStr = request.getParameter("minVoltage");
                double minVoltage = CommonWebUtil.getDoubleParameter(minVoltageStr, 0);

                String avgVoltageStr = request.getParameter("avgVoltage");
                double avgVoltage = CommonWebUtil.getDoubleParameter(avgVoltageStr, 0);

                String statusStr = request.getParameter("status");
                int status = CommonWebUtil.getIntParameter(statusStr, 0);

                String reasonAnalyze = request.getParameter("reasonAnalyze");

                String treatWay = request.getParameter("treatWay");

                String completeCase = request.getParameter("completeCase");

                String note = request.getParameter("note");

                String dataTimeStr = request.getParameter("dataTime");
                Timestamp dataTime = CommonWebUtil.getTimestampParamter(dataTimeStr);                

                String maxVoltageTimeStr = request.getParameter("maxVoltageTime");                
                Timestamp maxVoltageTime = CommonWebUtil.getTimestampParamter(maxVoltageTimeStr);                

                String minVoltageTimeStr = request.getParameter("minVoltageTime");
                Timestamp minVoltageTime = CommonWebUtil.getTimestampParamter(minVoltageTimeStr);
                
                result = ysjService.deleteByKey(pointId, dataYear, dataMonth, "");
                result = ysjService.add(deviceId, pointId, dataYear, dataMonth, dataTime, type, aboveUpperLimitNumber, underLowerLimitNumber,
                            defaultTotalTime, totalRunMin, aboveUpperLimitMin, underLowerLimitMin, maxVoltage, maxVoltageTime, minVoltage,
                            minVoltageTime, avgVoltage, reasonAnalyze, treatWay, completeCase, note);                
            }

            if (result) {
                out.println(JsonUtil.createSuccessJsonResponse(msg));
            } else {
                out.print(JsonUtil.createFailureJsonResponse("数据库操作失败"));
            }

        } catch (AlreadLockedException e) {
            String msg = e.getMessage();            
            out.print(JsonUtil.createFailureJsonResponse(msg));
            
        } catch (DuplicateKeyException e) {
            String msg = e.getMessage();
            if (msg.indexOf("NAME_t_voltageLevel") != -1) {
                out.print(JsonUtil.createFailureJsonResponse("名称不能和现有数据库中的记录重复"));
            }
        } catch (Exception e) {
            out.print(JsonUtil.createFailureJsonResponse("不明操作错误"));
            e.printStackTrace();
        } finally {
            out.close();
        }
    }

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
